import com.lowagie.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;


/**
 * Created by lyq on 2017/11/24.
 * 这个可以
 */

public class HtmlToPdf {

    public static void HtmltoPdfMethod(String inputFile,String outFile) throws Exception {
        OutputStream os = new FileOutputStream(outFile);
        ITextRenderer renderer = new ITextRenderer();
        String url = new File(inputFile).toURL().toURI().toString();
        renderer.setDocument(url);
        //解决中文支持问题
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont("C:/Windows/Fonts/simsunb.ttf", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        renderer.getSharedContext().setBaseURL("file:/E:/test");
        renderer.layout();
        renderer.createPDF(os);
        os.flush();
        os.close();
    }

    public static void main(String[] args) throws Exception {
        HtmltoPdfMethod("E:/1.html","E:/1.pdf");
    }
}
